package com.haiertvbic.timeline.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpDownloader {

	public static String download(String urlSrc) {
		StringBuffer sb = new StringBuffer();
		String line = "";
		BufferedReader buffer = null;
		InputStream inputStream = null;
		try {
			URL url = new URL(urlSrc);
			HttpURLConnection urlConn = (HttpURLConnection) url
					.openConnection();
			urlConn.setConnectTimeout(10 * 1000);
			urlConn.setReadTimeout(10 * 1000);
			urlConn.setDoOutput(true);
			urlConn.setRequestMethod("POST");
			inputStream = urlConn.getInputStream();

			buffer = new BufferedReader(new InputStreamReader(inputStream));
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}

		} catch (Exception e) {
			// e.printStackTrace();
			return "";
		} finally {
			try {
				if (inputStream != null)
					inputStream.close();
				if (buffer != null)
					buffer.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
		return sb.toString();
	}

	public static InputStream getInputStreamFromUrl(String urlSrc)
			throws IOException { 
		HttpGet httpRequest = new HttpGet(urlSrc);
		HttpClient httpclient = new DefaultHttpClient();
		try {
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity httpEntity = httpResponse.getEntity();
				return httpEntity.getContent();
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
